﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AccountManager.cs" company="Concept Architecture">
//   (c) 2010 Muhammad Umer Farooq
// </copyright>
// <summary>
//   Defines the  interface.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Hisaab.Business
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.Contracts;
    using System.Linq;
    using Common;
    using Data.Interfaces;
    using Entities;
    using Interfaces;

    using Microsoft.Practices.ServiceLocation;

    /// <summary>
    /// Defines the <seealso cref="Hisaab.Business.AccountManager"/> type.
    /// </summary>
    public class AccountManager : IAccountManager
    {
        /// <summary>
        /// Account repository
        /// </summary>
        private readonly IAccountRepository _accountRepository;

        /// <summary>
        /// Transaction repository
        /// </summary>
        private readonly ITransactionRepository _transactionRepository;

        /// <summary>
        /// Initializes a new instance of the <see cref="AccountManager"/> class.
        /// </summary>
        public AccountManager()
            : this(
            ServiceLocator.Current.GetInstance<IAccountRepository>(),
            ServiceLocator.Current.GetInstance<ITransactionRepository>())
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="AccountManager"/> class.
        /// </summary>
        /// <param name="accountRepository">The account repository.</param>
        /// <param name="transactionRepository">The transaction repository.</param>
        public AccountManager(IAccountRepository accountRepository, ITransactionRepository transactionRepository)
        {
            Contract.Requires<ArgumentNullException>(accountRepository != null);
            Contract.Requires<ArgumentNullException>(transactionRepository != null);
            _accountRepository = accountRepository;
            _transactionRepository = transactionRepository;
        }

        /// <summary>
        /// Gets the filtered.
        /// </summary>
        /// <param name="filter">The filter.</param>
        /// <param name="pageNo">The page no.</param>
        /// <param name="pageSize">Size of the page.</param>
        /// <returns>List of filtered items</returns>
        public IEnumerable<Account> List(Account filter, int? pageNo, int? pageSize)
        {
            return _accountRepository.Query(filter.Map<Account, Data.Entities.Account>(), pageNo, pageSize)
                .ToList()
                .Select(x => x.Map<Data.Entities.Account, Account>());
        }

        /// <summary>
        /// Adds the specified entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <returns>Id of account added</returns>
        public int Add(Account entity)
        {
            return _accountRepository.Add(entity.Map<Account, Data.Entities.Account>());
        }

        /// <summary>
        /// Updates the specified entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        public void Update(Account entity)
        {
            _accountRepository.Update(entity.Map<Account, Data.Entities.Account>());
        }

        /// <summary>
        /// Deletes the specified entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        public void Delete(Account entity)
        {
            _accountRepository.Delete(entity.Map<Account, Data.Entities.Account>());
        }

        /// <summary>
        /// Gets the by userId.
        /// </summary>
        /// <param name="id">The account userId.</param>
        /// <returns>Account matching account userId</returns>
        public Account GetById(int id)
        {
            return _accountRepository.FindById(id).Map<Data.Entities.Account, Account>();
        }

        /// <summary>
        /// Gets the name of the by.
        /// </summary>
        /// <param name="name">The name of account to get</param>
        /// <returns>Account matching name</returns>
        public Account GetByName(string name)
        {
            return _accountRepository.Query(new Data.Entities.Account { Name = name })
                .FirstOrDefault()
                .Map<Data.Entities.Account, Account>();
        }

        /// <summary>
        /// Gets the account summary.
        /// </summary>
        /// <param name="id">The account userId</param>
        /// <param name="userId">The user Id</param>
        /// <returns>Account summary object</returns>
        public AccountSummary GetAccountSummary(int id, int userId)
        {
            var transaction = new Data.Entities.Transaction { Account = id };
            var count = _transactionRepository.Query(transaction).Count();

            var transactions = _transactionRepository.Query(transaction);
            var transactionData = transactions.OrderBy(x => x.Date)
                .ToList()
                .GroupBy(x => x.Date.ToString("MMMM yyyy"));

            return new AccountSummary
                       {
                           TransactionCount = count,
                           EndingBalance = GetAccountBalance(id),
                           ChartData = transactionData.Select(data => new KeyValuePair<string, decimal>(data.Key, data.Sum(x => x.Amount))).ToArray()
                       };
        }

        /// <summary>
        /// Gets the account balance.
        /// </summary>
        /// <param name="id">The userId of account to get balance for</param>
        /// <returns>
        /// Closing balance of account
        /// </returns>
        public decimal GetAccountBalance(int id)
        {
            var total = _transactionRepository.Query(new Data.Entities.Transaction { Account = id }).ToList();
            return total.Sum(x => x.Amount);
        }

        /// <summary>
        /// Gets the monthly balance summary.
        /// </summary>
        /// <param name="accountId">The account userId.</param>
        /// <param name="userId">The calling user id</param>
        /// <returns>
        /// List of month and balance
        /// </returns>
        public IEnumerable<AccountMonthlyTotal> GetMonthlyBalanceSummary(int accountId, int userId)
        {
            var transaction = _accountRepository.GetMonthlyBalanceSummary(accountId)
                .ToList();

            decimal cumulativeTotal = 0;
            return transaction
                .Select(
                    x =>
                    {
                        var e = x.Map<Data.Entities.AccountMonthlyTotal, AccountMonthlyTotal>();
                        e.CumulativeTotal = cumulativeTotal += e.MonthlyTotal;
                        return e;
                    });
        }

        /// <summary>
        /// Gets the account totals.
        /// </summary>
        /// <param name="userId">The calling user id</param>
        /// <returns>
        /// List of account totals and summary
        /// </returns>
        public IEnumerable<KeyValue<Account, decimal>> GetAccountTotals(int userId)
        {
            return _accountRepository.GetAccountTotals(userId)
                .ToList()
                .Select(x => new KeyValue<Account, decimal> { Key = x.Key.Map<Data.Entities.Account, Account>(), Value = x.Value });
        }

        /// <summary>
        /// Gets all account balance.
        /// </summary>
        /// <param name="userId">The calling user id</param>
        /// <returns>
        /// Return list of accounts and all of their monthly totals
        /// </returns>
        public IEnumerable<KeyValue<Account, IEnumerable<AccountMonthlyTotal>>> GetAllAccountBalance(int userId)
        {
            var result = new List<KeyValue<Account, IEnumerable<AccountMonthlyTotal>>>();
            var accounts =
                _accountRepository.Query(new Data.Entities.Account { OwnerId = userId }).ToList().Select(
                    x => x.Map<Data.Entities.Account, Account>());

            foreach (var account in accounts)
            {
                var transaction = _accountRepository.GetMonthlyBalanceSummary(account.AccountId).ToList();

                decimal cumulativeTotal = 0;
                var accountmonthlyTotal = transaction
                    .Select(
                        x =>
                        {
                            var e = x.Map<Data.Entities.AccountMonthlyTotal, AccountMonthlyTotal>();
                            e.CumulativeTotal = cumulativeTotal += e.MonthlyTotal;
                            return e;
                        });

                result.Add(new KeyValue<Account, IEnumerable<AccountMonthlyTotal>> { Key = account, Value = accountmonthlyTotal });
                result.OrderBy(x => x.Key);
            }

            return result;
        }
    }
}